<?php
	$root = "data/";

	error_reporting(E_ALL);
	session_start();
	$nombre_estacion = $_SESSION['nombre_estacion'];
	$estacion = $nombre_estacion."/";
	$id_estacion = $_SESSION['estacion'];
	//$estacion = "BBB" . "/";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<style type="text/css">
	<!--
	body {
		background-color: #DBE8F9;
		font: 11px/24px "Trebuchet MS", "Trebuchet MS", Arial, Helvetica, sans-serif;
		color: #5A698B;
		padding-left:20px;
	}

	#title {
		width: 500px;
		height: 26px;
		color: #5A698B;
		font: bold 13px/21px "Trebuchet MS", "Trebuchet MS", Arial, Helvetica, sans-serif;
		padding-top: 5px;
		text-transform: uppercase;
		letter-spacing: 2px;
		text-align: left;
	}
	.input {
		background-color: #fff;
		font: 8px/10px "Trebuchet MS", Arial, Helvetica, sans-serif;
		color: #5A698B;
		margin: 1px 0 5px 8px;
		padding: 1px;
		border: 1px solid #8595B2;
	}

	.textarea {
		border: 1px solid #8595B2;
		background-color: #fff;
		font: 8px/10px "Trebuchet MS", "Trebuchet MS", Arial, Helvetica, sans-serif;
		color: #5A698B;
		margin: 4px 0 5px 8px;
	}

	.upload_message_success {
		padding:4px;
		background-color:#009900;
		border:1px solid #006600;
		color:#FFFFFF;
		margin-top:10px;
		margin-bottom:10px;
		overflow:hidden;
	}

	.upload_message_error {
		padding:4px;
		background-color:#CE3333;
		border:1px solid #990000;
		color:#FFFFFF;
		margin-top:10px;
		margin-bottom:10px;
		overflow:hidden;
	}

	-->
</style>
<script src="jquery.min.js" type="text/javascript"></script>
<script src="jquery.form.js" type="text/javascript"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
	$(document).ready(function() {
		$('#submitform').ajaxForm({
			target : '#oops',
			success : function() {
				$('#oops').fadeIn('slow');
			}
		});
	}); 
</script>

<meta http-equiv="content-type" content="type=text/html; charset=ISO-5589-1" />
<div id="title">&nbsp;ESTACION: <?php echo "". $nombre_estacion . ""; ?></div>
<link rel="stylesheet" type="text/css" href="file_manager/fmanager/fmanager.css" />
</head>
<body>
<div align="center">
<div id="body_matrix"><div id="body"><div id="body_border">
<div style="width:760px;height:25px;background:#eee;">
  <div style="line-height:25px;font-size:16px;color:#669EE9;font-weight:bold;">SUBIR IMAGENES Y ARCHIVOS AL SERVIDOR WEB</div></div>

<div id="oops"></div>

<?php
$agent = $_SERVER['HTTP_USER_AGENT'];
$ip = $_SERVER['REMOTE_ADDR'];
$ts = $_SERVER['REQUEST_TIME'];
$self = $_SERVER['PHP_SELF'];
$key = md5($agent . $ip . $ts . $self);
$uri = addslashes($_SERVER['REQUEST_URI']);
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$host = $_SERVER['HTTP_HOST'];
$domain = str_replace(array("www.", "cms.", "cpp."), "", $host);
$max_upload = (int)( ini_get('upload_max_filesize'));
$max_post = (int)( ini_get('post_max_size'));
$max_memory = (int)( ini_get('memory_limit'));
$upload_max = min($max_upload, $max_post, $max_memory);

function file_byte($a_bytes) {
	if ($a_bytes < 1024) {
		return $a_bytes . ' B';
	} elseif ($a_bytes < 1048576) {
		return round($a_bytes / 1024, 0) . ' KB';
	} elseif ($a_bytes < 1073741824) {
		return round($a_bytes / 1048576, 1) . ' MB';
	} elseif ($a_bytes < 1099511627776) {
		return round($a_bytes / 1073741824, 2) . ' GB';
	} elseif ($a_bytes < 1125899906842624) {
		return round($a_bytes / 1099511627776, 2) . ' TB';
	} elseif ($a_bytes < 1152921504606846976) {
		return round($a_bytes / 1125899906842624, 2) . ' PB';
	} elseif ($a_bytes < 1180591620717411303424) {
		return round($a_bytes / 1152921504606846976, 2) . ' EB';
	} elseif ($a_bytes < 1208925819614629174706176) {
		return round($a_bytes / 1180591620717411303424, 2) . ' ZB';
	} else {
		return round($a_bytes / 1208925819614629174706176, 2) . ' YB';
	}
}

function dirsize($directory) {
	$size = 0;
	foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
		$size += $file -> getSize();
	}
	return $size;
}

function sendPgdatos($root,  $id_estacion, $estacion, $subsc) {
	include "../database.php";
	$descpBox = $_POST['subsc'];
	$con = pg_connect("user=" . DB_USER . " port=" . DB_PORT . " dbname=" . DB_NAME . " host=" . DB_HOST . " password=" . DB_PASS) or die("No se puede conectar a la base de datos !\n");

	$file_name = '' . $root . '' . $estacion . '' . $subsc . '';
	$img = fopen($file_name, 'r') or die("no c puede abrir archivo");
	$data = fread($img, filesize($file_name));
	$es_data = pg_escape_bytea($data);
	$query = "INSERT INTO hsig.estacion_imagen(estacion_id,nm_nombre,tipo_imagen,objeto) Values($id_estacion,'$file_name','E','$es_data')";
	if (!pg_query($con, $query)) {
		echo '<p>';
		echo "not inserted en base de datos";

		fclose($img);
		pg_close($con);

	}
}

function filename_safe($name) {
	$except = array('#', '=', '!', '\\', '/', ':', ';', '*', '?', '"', '<', '>', '|', '{', '}', '%', '�', '\'', '(', ')', '$', '�', '�', '`', '~', '�', '^', ',', '&');
	return str_replace($except, '', $name);
}

//$type = $_GET['type'];
//if($type == "1") { $type = "dir"; } else { $type = "file"; }

$dir = $estacion;
if ($dir == null || $dir == "." || $dir == "/" || $dir == "./" || $dir[0] == "/" || substr($dir, -2) == ".." || substr($dir, -2) == "./" || substr($dir, -2) == "//" || substr($dir, -1) == ".") { $dir = $root;
}
if (substr($dir, 0, strlen($root)) != $root) { $dir = $root . $dir;
}
$path = $dir;

$folder = explode('/', $path, -1);
$count = count(explode('/', $path, -1));
$count = $count - 1;

/*$uri = $_GET['uri'];
 $uri_path = explode('/', $uri, -1);
 $uri_count = count(explode('/', $uri, -1));
 $uri_count = $uri_count-1;*/

$css_row = 0;

$title = $path;
if ($count >= 2) {
	$title = $folder[0] . '/';
	$slashes = $count - 1;
	while ($slashes > 0) {
		$title .= '../';
		$slashes--;
	}
	$title .= $folder[$count];
	$title .= '/';
}

$strip_last = strlen($folder[$count]) + 1;
$up = substr($path, 0, -$strip_last);

//echo '<div id="h2"><span style="color:#bbb;">Upload archivos en</span> '.$estacion.'</div>'."\n";

echo '<div style="width:760px;height:100px;background:#f9f9f9;border-bottom:1px solid #eee;" align="center">' . "\n";
echo '   <form action="upload-files.php?exec=upload&dir=' . $dir . '" method="post" enctype="multipart/form-data">' . "\n";
echo '   <div style="width:700px;" align="center">' . "\n";
echo '   <table align="center" height="100" cellspacing="0" cellpadding="0"><tr>' . "\n";
echo '   <td valign="middle"><img src="file_manager/fmanager/document_new.png" height="32" width="32" border="0" /></td>' . "\n";
echo '   <td valign="middle">Nombre del Archivo: <input type="text" name="subsc" id="subsc" style="width:100px;height:20px;"></td>' . "\n";
echo '   <td valign="middle">&nbsp;<input type="file" class="input" style="height:20px;" name="upload" /></td>' . "\n";
echo '   <td valign="middle"><input type="submit" class="submit" value=" Enviar " name="exec"/></td>' . "\n";
echo '   </tr></table>' . "\n";
echo '   </div>' . "\n";
echo '   </form>';
echo '</div>';

if (isset($_GET['exec']) && ($_POST['subsc'] != "")) {

	$exec = $_GET['exec'];
	$filename = $_FILES['upload']['name'];
	$path_info = pathinfo($filename);
	if ($filename != "") {$ext = $path_info['extension'];
		$subsc = $_POST['subsc'] . "." . $ext . "";
	}

	if (file_exists($_FILES['upload']['tmp_name'])) {
		if (!is_dir('' . $root . '' . $estacion . '')) {
			mkdir('' . $root . '' . $estacion . '') or die('<div id="oops" class="upload_message_error">No tiene permiso para crear la carpeta.</div>');
		}
		move_uploaded_file($_FILES['upload']['tmp_name'], $dir . filename_safe($subsc));
		//sendmail();
		sendPgdatos($root, $id_estacion, $estacion, $subsc);
		echo '   <table align="top" height="10" width = "100%" cellspacing="0" cellpadding="0"><tr>';
		echo '   <td colspan="1" height="10" valign="top" align="center" class="upload_message_success">Archivo almacenado satisfactoriamente.</td>';
		echo '   </tr></table>' . "\n";

	}
} else {
	echo '<div id="oops" class="upload_message_error"> Se debe seleccionar el archivo y darle un nombre</div>';
}//}
?>

</div>
</div>
</div>
</div>
</body>
</html>
